﻿package utils
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	import org.bytearray.explorer.SWFExplorer;
	

	/**
	 * swf分析类
	 * @author jcg
	 */
	public class SwfParser
	{
		private var _swfData:ByteArray;
		private var _loader:Loader;
		private var _completed:Boolean; 
		
		public function SwfParser()
		{
			init();
		}
		
		private function init():void
		{
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderEventHandler);
		}
		
		private function loaderEventHandler(e:Event):void
		{
			var explorer:SWFExplorer = new SWFExplorer();
			var classes:Array = explorer.parse(_swfData);
			_completed = true;
			completeFunc();
		}
		
		private function clearAll():void
		{
			_swfData = null;
			_completed = false;
		}
		
		/**
		 * param swf
		 * 解析一个swf
		 */
		public function parseSwf(swf:ByteArray):void
		{
			clearAll();
			
			_swfData = swf;
			var loaderContext:LoaderContext = new LoaderContext(); 
　　			loaderContext.allowLoadBytesCodeExecution = true; 
			_loader.loadBytes(_swfData, loaderContext);
		}
		
		/**
		 * 指定的解析完毕要执行的函数
		 */
		public var completeFunc:Function;
		
		/**
		 * 获得解析的swf的二进制数据
		 */
		public function get swfData():ByteArray
		{
			return _swfData;
		}
		
		/**
		 * 通过类名或许类
		 */
		public function getClass(className:String):Class
		{
			if(_loader.contentLoaderInfo.applicationDomain.hasDefinition(className))
				return _loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class;
			
			return null;
		}
		
		/**
		 * 是否解析完毕
		 */
		public function get completed():Boolean
		{
			return _completed;
		}
	}
}